package org.nighthawkhosting.SC2Mapster;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ForumView extends ListActivity {
	private ArrayList<Forum> forumList = null;
	private ForumAdapter adapter;
	private ArrayList<Cookie> cookieData = new ArrayList<Cookie>();
	private Runnable fillDataRunnable;
	private ProgressDialog progress;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.forumlist);
		if(savedInstanceState != null) {
			Bundle cookieBundle = savedInstanceState.getBundle("_cookies");
			for(int i = 0; i < cookieBundle.size(); i++) {
				cookieData.add(CookieParser.parse(cookieBundle.getStringArrayList(String.valueOf(i))));
			}
		}

		fillDataRunnable = new Runnable(){
			@Override
			public void run() {
				fillData();
			}
		};
		
		Thread thread =  new Thread(null, fillDataRunnable, "MagentoBackground");
		thread.start();
		registerForContextMenu(getListView());
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		//super.onCreateContextMenu(menu, v, menuInfo);
		//menu.add(0, DELETE_ID, 0, R.string.menu_delete);
		AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo;
		Long place = new Long(info.id);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(adapter.getItem(place.intValue()).getForumDescription());
		AlertDialog alert = builder.create();
		alert.setCanceledOnTouchOutside(true);
		alert.show();
	}

	private void fillData() {
		handler.sendEmptyMessage(0);
		try {
			ForumParser parser = new ForumParser();
			parser.setURL("http://forums.sc2mapster.com/");
			parser.setCookieData(this.cookieData);
			forumList = parser.parse();
			handler.sendEmptyMessage(2);
			Thread.sleep(100);
		} catch (Exception e) {
			Log.e("BACKGROUND_PROC", e.getMessage());
		}
		handler.sendEmptyMessage(1);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				progress = ProgressDialog.show(ForumView.this, "", "Retrieving data ...", true);
			} else if (msg.what == 1) {
				progress.dismiss();
			} else if (msg.what == 2) {
				adapter = new ForumAdapter(ForumView.this, R.layout.forumrow, forumList);
				setListAdapter(adapter);
				adapter.notifyDataSetChanged();
			}
			//pd.dismiss();
			//tv.setText(pi_string);
		}
	};

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		if(forumList.get(position).isForumSuper())
			return;

		Intent i = new Intent(this, ThreadView.class);
		i.putExtra("_title", forumList.get(position).getForumTitle());
		i.putExtra("_url", "http://forums.sc2mapster.com" + forumList.get(position).getForumURL());

		Bundle cookieBundle = new Bundle();
		for (int i2 = 0; i2 < cookieData.size(); i2++) {			
			cookieBundle.putStringArrayList(String.valueOf(i2), CookieParser.parse(cookieData.get(i2)));
		}

		i.putExtra("_cookies", cookieBundle);
		//this.startActivity(i);
		startActivityForResult(i, 1);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, Menu.FIRST, 0, "Login");
		menu.add(0, Menu.FIRST+1, 0, "Refresh");
		return true;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Bundle cookieBundle = new Bundle();
		for (int i2 = 0; i2 < cookieData.size(); i2++) {			
			cookieBundle.putStringArrayList(String.valueOf(i2), CookieParser.parse(cookieData.get(i2)));
		}
		outState.putBundle("_cookies", cookieBundle);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()) {
		case Menu.FIRST:
			loginWindow();
			return true;
		case Menu.FIRST+1:
			Thread thread =  new Thread(null, fillDataRunnable, "MagentoBackground");
			thread.start();
			//fillDataThread.start();
			return true;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	private void login(String username, String password) {
		try{
			DefaultHttpClient client = new DefaultHttpClient();

			HttpGet request = new HttpGet("http://www.sc2mapster.com/home/login/");
			client.execute(request);

			HttpPost httppost = new HttpPost("http://www.sc2mapster.com/home/login/");
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);  
			nameValuePairs.add(new BasicNameValuePair("form_type", "login"));  
			nameValuePairs.add(new BasicNameValuePair("login_username", username));
			nameValuePairs.add(new BasicNameValuePair("login_password", password));  
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));   
			client.execute(httppost);

			List<Cookie> tempList = client.getCookieStore().getCookies();
			for (int i = 0; i < tempList.size(); i++) {
				this.cookieData.add(tempList.get(i));
			}
			Thread thread =  new Thread(null, fillDataRunnable, "MagentoBackground");
			thread.start();
		} catch (Exception e) {

		}
	}

	private void loginWindow() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		//alert.setTitle("Title");
		//alert.setMessage("Message");

		// Set an EditText view to get user input 
		Context mContext = getApplicationContext();
		LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
		final View layout = inflater.inflate(R.layout.login,
				(ViewGroup) findViewById(R.id.layout_root));
		alert.setView(layout);

		alert.setPositiveButton("Login", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
				EditText username = (EditText) layout.findViewById(R.id.username);
				EditText password = (EditText) layout.findViewById(R.id.password);
				login(username.getText().toString(), password.getText().toString());
			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();
	}

	public class ForumAdapter extends ArrayAdapter<Forum> {

		private ArrayList<Forum> forums;

		public ForumAdapter(Context context, int textViewResourceId, ArrayList<Forum> items) {
			super(context, textViewResourceId, items);
			this.forums = items;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Forum data = forums.get(position);
			View v = convertView;

			if (data == null) return v;

			if (data.isForumSuper()) {
				TextView tv = new TextView(getContext());
				tv.setText(data.getForumTitle());
				tv.setTextSize(18);
				return tv;
			} else {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.forumrow, null);

				ImageView icon = (ImageView) v.findViewById(R.id.icon);
				TextView title = (TextView) v.findViewById(R.id.forumtitle);
				TextView description = (TextView) v.findViewById(R.id.forumdescription);
				
				title.setText(data.getForumTitle());
				description.setText(data.getForumDescription());
				
				if(data.getForumStatus().equals("Read"))
					icon.setImageResource(R.drawable.read);

				return v;
			}
		}
	}
}